package com.sanqing.main;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class PasswordDialog extends JDialog {
    private boolean isAuthenticated = false;
    private JPasswordField passwordField;

    public PasswordDialog(JFrame parent) {
        super(parent, "权限验证", true); // 模态对话框
        setSize(300, 150);
        setLocationRelativeTo(parent); // 居中显示
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        setLayout(new BorderLayout());

        // 中间内容面板
        JPanel contentPanel = new JPanel(new BorderLayout(10, 10));
        contentPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        JLabel tipLabel = new JLabel("请输入操作密码：", SwingConstants.CENTER);
        passwordField = new JPasswordField(15);
        passwordField.setEchoChar('●'); // 设置密码显示字符
        
        contentPanel.add(tipLabel, BorderLayout.NORTH);
        contentPanel.add(passwordField, BorderLayout.CENTER);
        add(contentPanel, BorderLayout.CENTER);

        // 底部按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton confirmBtn = new JButton("确认");
        JButton cancelBtn = new JButton("取消");
        
        confirmBtn.addActionListener(e -> handleConfirm());
        cancelBtn.addActionListener(e -> dispose()); // 取消则关闭对话框
        
        buttonPanel.add(confirmBtn);
        buttonPanel.add(cancelBtn);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void handleConfirm() {
        String inputPassword = new String(passwordField.getPassword());
        if ("0000".equals(inputPassword)) {
            isAuthenticated = true;
            dispose(); // 验证通过关闭对话框
        } else {
            JOptionPane.showMessageDialog(this, "密码错误，请重新输入！", 
                "错误提示", JOptionPane.ERROR_MESSAGE);
            passwordField.selectAll(); // 选中密码文本以便重新输入
        }
    }

    public boolean showDialog() {
        setVisible(true);
        return isAuthenticated;
    }
}